@{
    var isEmbed = Context?.Request?.Query["embed"].ToString() == "1";
    Layout = isEmbed ? null : "_Layout";
    ViewData["Title"] = "BOM管理";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<style>
    .bom-container {
        padding: 20px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    .bom-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .bom-actions {
        display: flex;
        gap: 10px;
    }
    
    .btn-primary {
        background: #1e88e5;
        border: none;
        color: white;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }
    
    .btn-primary:hover {
        background: #1565c0;
    }
    
    .search-box {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .search-input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        width: 200px;
        font-size: 14px;
    }
    
    .search-input:focus {
        outline: none;
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
    }
    
    .bom-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }
    
    .bom-table th,
    .bom-table td {
        padding: 12px 8px;
        text-align: left;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .bom-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }
    
    .bom-table tr:nth-child(even) {
        background: #f9fafb;
    }
    
    .bom-table tr:hover {
        background: #f0f4ff;
    }
    
    .checkbox-cell {
        width: 40px;
        text-align: center;
    }
    
    .checkbox {
        width: 16px;
        height: 16px;
        cursor: pointer;
    }
    
    .action-buttons {
        display: flex;
        gap: 5px;
    }
    
    .btn-edit {
        background: #28a745;
        color: white;
        border: none;
        padding: 4px 8px;
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px;
    }
    
    .btn-delete {
        background: #dc3545;
        color: white;
        border: none;
        padding: 4px 8px;
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px;
    }
    
    .pagination-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #e5e7eb;
    }
    
    .pagination-info {
        color: #666;
        font-size: 14px;
    }
    
    .pagination-controls {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .page-btn {
        padding: 6px 12px;
        border: 1px solid #ddd;
        background: white;
        color: #333;
        cursor: pointer;
        border-radius: 3px;
        font-size: 14px;
    }
    
    .page-btn:hover {
        background: #f8f9fa;
    }
    
    .page-btn.active {
        background: #1e88e5;
        color: white;
        border-color: #1e88e5;
    }
    
    .page-btn:disabled {
        background: #f8f9fa;
        color: #ccc;
        cursor: not-allowed;
    }
    
    .page-size-selector {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    
    .page-size-select {
        padding: 4px 8px;
        border: 1px solid #ddd;
        border-radius: 3px;
        font-size: 14px;
    }
    
    .refresh-btn {
        background: none;
        border: none;
        color: #666;
        cursor: pointer;
        font-size: 16px;
        padding: 4px;
    }
    
    .refresh-btn:hover {
        color: #1e88e5;
    }
    
    .go-to-page {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    
    .page-input {
        width: 50px;
        padding: 4px 8px;
        border: 1px solid #ddd;
        border-radius: 3px;
        text-align: center;
        font-size: 14px;
    }
    
    .confirm-btn {
        background: #1e88e5;
        color: white;
        border: none;
        padding: 4px 8px;
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px;
    }
    
    .loading {
        text-align: center;
        padding: 20px;
        color: #666;
    }
    
    .error-message {
        text-align: center;
        padding: 20px;
        color: #dc3545;
    }
</style>

<div class="bom-container">
    <!-- 头部操作区域 -->
    <div class="bom-header">
        <div class="bom-actions">
            <button class="btn-primary" onclick="addBOM()">
                <i class="fas fa-plus"></i> 新增
            </button>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" placeholder="请输入BOM编号" id="searchInput">
            <button class="btn-primary" onclick="searchBOM()">
                <i class="fas fa-search"></i> 搜索
            </button>
        </div>
    </div>
    
    <!-- BOM表格 - 新的字段结构 -->
    <table class="bom-table">
        <thead>
            <tr>
                <th class="checkbox-cell">
                    <input type="checkbox" class="checkbox" id="selectAll" onchange="toggleSelectAll()">
                </th>
                <th>序号</th>
                <th>BOM编号</th>
                <th>主题</th>
                <th>版本</th>
                <th>成品名称</th>
                <th>成品编号</th>
                <th>日产量</th>
                <th>单件成本</th>
                <th>单日预估成本</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="bomTableBody">
            <!-- 数据行将通过JavaScript动态生成 -->
        </tbody>
    </table>
    
    <!-- 分页控制 -->
    <div class="pagination-container">
        <div class="pagination-info">
            共 <span id="totalCount">0</span> 条
        </div>
        
        <div class="pagination-controls">
            <button class="page-btn" id="prevBtn" onclick="previousPage()" disabled>上一页</button>
            
            <div id="pageNumbers" class="page-numbers">
                <!-- 页码按钮将通过JavaScript动态生成 -->
            </div>
            
            <button class="page-btn" id="nextBtn" onclick="nextPage()" disabled>下一页</button>
            
            <div class="page-size-selector">
                <span>每页</span>
                <select class="page-size-select" id="pageSizeSelect" onchange="changePageSize()">
                    <option value="5">5条</option>
                    <option value="10" selected>10条</option>
                    <option value="15">15条</option>
                    <option value="20">20条</option>
                </select>
            </div>
            
            <button class="refresh-btn" onclick="refreshData()" title="刷新">
                <i class="fas fa-sync-alt"></i>
            </button>
            
            <div class="go-to-page">
                <span>到第</span>
                <input type="number" class="page-input" id="goToPageInput" min="1" value="1">
                <span>页</span>
                <button class="confirm-btn" onclick="goToPage()">确定</button>
            </div>
        </div>
    </div>
</div>

<script>
    // 分页相关变量
    let currentPage = 1;
    let pageSize = 10;
    let totalCount = 0;
    let totalPages = 0;
    let bomData = [];
    let searchBomCode = '';
    
    // API接口地址 - 使用图二中的接口
    const API_BASE_URL = 'http://localhost:5287/api/BomManage/BomQuery';
    
    // 页面加载完成后初始化
    $(document).ready(function() {
        console.log('BOM列表页面已加载 - 新版本');
        console.log('API地址:', API_BASE_URL);
        loadBOMData();
    });
    
    // 加载BOM数据 - 调用图二中的API接口
    function loadBOMData() {
        showLoading();
        
        // 构建查询参数 - 对应图二中的参数
        const params = new URLSearchParams({
            PageIndex: currentPage,
            PageSize: pageSize
        });
        
        // 如果有搜索条件，添加BOM编号查询
        if (searchBomCode.trim()) {
            params.append('BomCode', searchBomCode.trim());
        }
        
        console.log('发起API请求:', `${API_BASE_URL}?${params.toString()}`);
        
        // 发起Ajax请求
        $.ajax({
            url: `${API_BASE_URL}?${params.toString()}`,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                console.log('API响应成功:', response);
                
                if (response.code === 200) {
                    // 成功获取数据
                    const data = response.data;
                    bomData = data.list || [];
                    totalCount = data.totalCount || 0;
                    totalPages = data.totalPages || 0;
                    
                    // 更新分页信息
                    if (data.pageIndex !== undefined && data.pageIndex !== null) {
                        currentPage = data.pageIndex + 1; // API返回的pageIndex从0开始
                    }
                    
                    renderTable();
                    renderPagination();
                    updatePaginationState();
                } else {
                    // API返回错误
                    showError(`获取数据失败: ${response.message || '未知错误'}`);
                }
            },
            error: function(xhr, status, error) {
                console.error('Ajax请求失败:', error);
                console.error('状态:', status);
                console.error('响应文本:', xhr.responseText);
                showError(`请求失败: ${error}`);
            }
        });
    }
    
    // 显示加载状态
    function showLoading() {
        const tbody = document.getElementById('bomTableBody');
        tbody.innerHTML = '<tr><td colspan="11" class="loading">正在加载数据...</td></tr>';
    }
    
    // 显示错误信息
    function showError(message) {
        const tbody = document.getElementById('bomTableBody');
        tbody.innerHTML = `<tr><td colspan="11" class="error-message">${message}</td></tr>`;
    }
    
    // 渲染表格 - 使用图二中的字段映射
    function renderTable() {
        const tbody = document.getElementById('bomTableBody');
        
        if (bomData.length === 0) {
            tbody.innerHTML = '<tr><td colspan="11" class="loading">暂无数据</td></tr>';
            return;
        }
        
        let html = '';
        bomData.forEach((item, index) => {
            const rowNumber = (currentPage - 1) * pageSize + index + 1;
            
            // 计算单日预估成本 = 单件成本 × 日产量
            const dailyCost = (item.oneprice || 0) * (item.dayPlannum || 0);
            
            html += `
                <tr>
                    <td class="checkbox-cell">
                        <input type="checkbox" class="checkbox" value="${item.id}">
                    </td>
                    <td>${rowNumber}</td>
                    <td>${item.bomCode || '-'}</td>
                    <td>${item.bomTopic || '-'}</td>
                    <td>${item.bomVersion || '-'}</td>
                    <td>${item.goodsName || '-'}</td>
                    <td>${item.goodsCode || '-'}</td>
                    <td>${item.dayPlannum || 0}</td>
                    <td>${item.oneprice || 0}</td>
                    <td>${dailyCost}</td>
                    <td class="action-buttons">
                        <button class="btn-edit" onclick="editBOM(${item.id})">编辑</button>
                        <button class="btn-delete" onclick="deleteBOM(${item.id})">删除</button>
                    </td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
        console.log('表格渲染完成，数据行数:', bomData.length);
    }
    
    // 渲染分页
    function renderPagination() {
        const pageNumbers = document.getElementById('pageNumbers');
        let html = '';
        
        // 显示最多5个页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
        
        // 调整起始页，确保显示足够的页码
        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage ? 'active' : '';
            html += `<button class="page-btn ${isActive}" onclick="goToPageNumber(${i})">${i}</button>`;
        }
        
        pageNumbers.innerHTML = html;
    }
    
    // 更新分页状态
    function updatePaginationState() {
        document.getElementById('prevBtn').disabled = currentPage === 1;
        document.getElementById('nextBtn').disabled = currentPage === totalPages || totalPages === 0;
        document.getElementById('totalCount').textContent = totalCount;
        document.getElementById('goToPageInput').value = currentPage;
    }
    
    // 全选/取消全选
    function toggleSelectAll() {
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('#bomTableBody .checkbox');
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAll.checked;
        });
    }
    
    // 搜索BOM - 支持BOM编号查询
    function searchBOM() {
        searchBomCode = document.getElementById('searchInput').value.trim();
        console.log('搜索BOM编号:', searchBomCode);
        
        // 重置到第一页并重新加载数据
        currentPage = 1;
        loadBOMData();
    }
    
    // 新增BOM
    function addBOM() {
        console.log('新增BOM');
        // 跳转到新增BOM页面
        if (window.parent && window.parent.loadContent) {
            // 如果在iframe中，通知父页面加载新增页面
            window.parent.postMessage({ 
                action: 'loadBOMAdd',
                url: '/Process/BOMAdd',
                title: '新增BOM'
            }, '*');
        } else {
            // 如果不在iframe中，直接跳转
            window.location.href = '/Process/BOMAdd';
        }
    }
    
    // 编辑BOM
    function editBOM(id) {
        console.log('编辑BOM:', id);
        // 这里可以实现编辑BOM的逻辑
        alert(`编辑BOM ID: ${id}`);
    }
    
    // 删除BOM
    function deleteBOM(id) {
        console.log('删除BOM:', id);
        if (confirm('确定要删除这个BOM吗？')) {
            // 这里可以实现删除BOM的逻辑
            alert(`删除BOM ID: ${id}`);
        }
    }
    
    // 上一页
    function previousPage() {
        if (currentPage > 1) {
            currentPage--;
            loadBOMData();
        }
    }
    
    // 下一页
    function nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            loadBOMData();
        }
    }
    
    // 跳转到指定页码
    function goToPageNumber(pageNum) {
        if (pageNum >= 1 && pageNum <= totalPages) {
            currentPage = pageNum;
            loadBOMData();
        }
    }
    
    // 跳转到指定页面
    function goToPage() {
        const input = document.getElementById('goToPageInput');
        const pageNum = parseInt(input.value);
        
        if (pageNum >= 1 && pageNum <= totalPages) {
            currentPage = pageNum;
            loadBOMData();
        } else {
            alert('请输入有效的页码！');
            input.value = currentPage;
        }
    }
    
    // 改变每页显示数量
    function changePageSize() {
        const select = document.getElementById('pageSizeSelect');
        pageSize = parseInt(select.value);
        currentPage = 1; // 重置到第一页
        loadBOMData();
    }
    
    // 刷新数据
    function refreshData() {
        console.log('刷新数据');
        loadBOMData();
    }
    
    // 回车键搜索
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchBOM();
        }
    });
</script>
